package cl.sms.service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
import cl.webservice.WebserviceSms;
import cl.webservice.WebserviceUpdateSms;
import com.google.gson.Gson;

public class SmsService extends Service {

	private static final long POLL_INTERVAL = 30000; // every minute
	private String NENVIOSMS = "Han sido enviados nuevos SMS";
	private Timer timer = null;
	private WebserviceSms wsms = new WebserviceSms();
	private WebserviceUpdateSms wsups = new WebserviceUpdateSms();
	private int[] idsSms;
	private BroadcastReceiver myreceiver1;
	private BroadcastReceiver  myreceiver2;
	private Boolean iniciarreceiver = Boolean.FALSE;



	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Log.i("SMSService", "Me ubico en onCreate");
		Toast.makeText(this, "SMSService.onCreate()", Toast.LENGTH_LONG).show();
		//		inicialreceiver();


	}

	@Override
	public void onStart(Intent intent, int startid) {

		super.onStart(intent, startid);
		Log.i("SMSService", "me ubico en onstart");
		Toast.makeText(this, "SMSService.onstart()", Toast.LENGTH_LONG).show();
		//Reviza si existe configuracion de servidor en el sistema
		SharedPreferences prefs = getSharedPreferences("Configuracion",Context.MODE_PRIVATE);   
		String servidor = prefs.getString("selectServidor", "");
		if(servidor.equals(""))
			Toast.makeText(getApplicationContext(), "No existe servidor configurado en  el sistema, vea esto en CONFIGURACIONES de la app", 30).show();

		if (this.timer != null) {
			this.timer.cancel();
		}
		this.timer = new Timer();
		this.timer.schedule(new ServiceTimeTaskSMS(this), 5000, POLL_INTERVAL);

	}


	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.i("SMSService", "Me ubico en onBind");
		Toast.makeText(this, "SMSService.onBind()", Toast.LENGTH_LONG).show();
		return null;
	}





	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		/**Se cancela el proceso de Notificaciones*/
		NotificationManager nm;  
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.cancelAll();

		if(iniciarreceiver){
			unregisterReceiver(myreceiver1);
			unregisterReceiver(myreceiver2);
		}

		Log.i("SMSService", "Me ubico en destroy");
		Toast.makeText(this, "SMSService.onDestroy()", Toast.LENGTH_LONG).show();
		if (this.timer != null) {
			this.timer.cancel();
		}
		Log.i(getClass().getSimpleName(), "Timer stopped.");


	}


	/**
	 * Muestra una notificion en la pantalla del dispositivo
	 * @param notificacion String
	 */
	private void showNotification(String notificacion) {  
		NotificationManager nm; 
		CharSequence contentTitle = "Envio Sms dice: ";  // titulo mensaje
		CharSequence contentText = notificacion;      // texto mensaje

		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
		Intent intent = new Intent(this, SmsService.class);  
		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); 

		Notification notification = new Notification();  
		notification.icon = R.drawable.notifica;  
		//		notification.defaults = Notification.DEFAULT_ALL;  
		notification.setLatestEventInfo(this, contentTitle, contentText, pi);  
		nm.notify(0, notification);  
	}  


	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.i("SMSService", "Me ubico en onUnbind");
		Toast.makeText(this, "SMSServicee.onUnbind()", Toast.LENGTH_LONG).show();
		return super.onUnbind(intent);
	}

	/**
	 * 
	 * @author MariaJose
	 *
	 */
	private class ServiceTimeTaskSMS extends TimerTask {
		private Service service;
		private ServiceTimeTaskSMS(Service service) {
			this.service = service;
		}


		public void run() {
			Log.i("MySmsService", "Me ubico en Run de la clase smsService");
			callWs();
		}
	}

	/**
	 * 
	 */
	public void callWs(){

		/**
		 * se llama al json del ws
		 */
		SharedPreferences prefs = getSharedPreferences("Configuracion",Context.MODE_PRIVATE);   
		String servidor = prefs.getString("selectServidor", "");
		
		if(!servidor.equals("")){
			String datosJsonString = wsms.obtenerSms(servidor);
			Log.i("informacion",datosJsonString);
			
			if(!datosJsonString.equals("[]")){
				JSONArray jsonContent;

				try {
					jsonContent = new JSONArray(datosJsonString);
					int numItems = jsonContent.length();
					idsSms = new int[numItems];/*declaro un arreglo de id de sms*/
					for (int i = 0; i < numItems; i++) {

						JSONObject item = jsonContent.getJSONObject(i);

						String numeroenvio = item.getString("numneroenvio");

						String numerodestino = item.getString("numerodestino");

						String mensaje = item.getString("mensaje");


						sendSMS(numerodestino, mensaje);
						//guarda el id del sms en un lista
						idsSms[i] = Integer.valueOf(item.getString("id"));
					}


					/**
					 * Para el cambio de estado en la bd
					 */
					Gson gson = new Gson();
					String jsonIdSms = gson.toJson(idsSms);

					/**
					 * Envia los id al ws de actualizacion de estado
					 */
					String resultUpdate = wsups.updateSms(jsonIdSms,servidor);

					if(resultUpdate.equals("1")){

						Log.i("webserviceactualizacion","se actualizo");
					}else 
						Log.i("webserviceactualizacion","no se actualizo");
					/**
					 * envia Notificacion al usuario
					 */
					showNotification(NENVIOSMS);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				Log.i("EnviarSms", "No se encontraron datos en el ws");
			}
		}else{
			Toast.makeText(getApplicationContext(), "No hay servidor configurado", 10).show();
		}
	}

	/**
	 * 
	 */
	private void sendSMS(String phoneNumber, String message)
	{        
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";
		iniciarreceiver = Boolean.TRUE;

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
				new Intent(SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);


		//---when the SMS has been sent---
		registerReceiver(myreceiver1 = new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Log.i("okMSM", "ok");
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					break;
				}
			}
		}, new IntentFilter(SENT));

		//---when the SMS has been delivered---
		registerReceiver(myreceiver2 = new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					break;
				case Activity.RESULT_CANCELED:
					break;                        
				}
			}
		}, new IntentFilter(DELIVERED));        

		SmsManager sms = SmsManager.getDefault();
		//sms.sendDataMessage(phoneNumber, "",new  , message, sentPI, deliveredPI);
		sms.sendTextMessage(phoneNumber, null, message, null, null);        
	}

}